package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserAddDto;
import com.zzyl.dto.UserPageDto;
import com.zzyl.dto.UserUpdateDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.UserPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public PageResponse userPage(Integer pageNum, Integer pageSize, UserPageDto dto) {
        PageHelper.startPage(pageNum, pageSize);

        if (!StringUtils.isEmpty(dto.getDeptNo())) {
            dto.setDeptNo(NoProcessing.processString(dto.getDeptNo()));
        }

        Page<UserPageVo> userPageVos = userMapper.userPage(dto);
        List<UserPageVo> result = userPageVos.getResult();
        if (!CollectionUtils.isEmpty(result)) {
            result.forEach((vo) -> {
                vo.setRoleVoIds(StringUtils.isEmpty(vo.getRoleIds()) ? new ArrayList<>() : Arrays.asList(vo.getRoleIds().split(",")));
                vo.setRoleLabels(StringUtils.isEmpty(vo.getRoleNames()) ? new ArrayList<>() : Arrays.asList(vo.getRoleNames().split(",")));
            });
        }
        return PageResponse.of(userPageVos, UserPageVo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(UserAddDto dto) {
        //判断用户名是否重复
        User userDB =userMapper.selectByEmail(dto.getEmail());
        if(userDB != null){
            throw new BaseException(BasicEnum.DATA_EXIST);
        }
        User user = BeanUtil.copyProperties(dto, User.class);
        //生成初始密码
        user.setPassword(BCrypt.hashpw("123456"));
        //用户名为邮箱
        user.setUsername(dto.getEmail());
        //设置用户类型
        if (!Objects.isNull(dto.getPostNo()) && !dto.getPostNo().isEmpty()) {
            user.setUserType(SuperConstant.DATA_STATE_0);
        } else {
            user.setUserType(SuperConstant.DATA_STATE_1);
        }
        //添加用户
        userMapper.insertSelective(user);
        //添加关联表
        insertUserRole(user.getId(),dto.getRoleVoIds());
    }

    @Override
    public void updateUserPassword(Long userId) {
        String resetPassword = BCrypt.hashpw("123456");
        userMapper.updateUserPassword(userId,resetPassword);
    }

    @Override
    public void updateUserStatus(Long id, Integer status) {
        userMapper.updateUserStatus(id,status);
    }

    @Override
    public void removeUser(Long userIds) {
        //先判断用户状态
        User user = userMapper.selectByPrimaryKey(userIds);
        if(user != null){
            if(user.getDataState().equals("0")){
                throw new BaseException(BasicEnum.ENABLED_CANNOT_DELETED);
            }
        }else {
            throw new BaseException(BasicEnum.USER_NOT_EXIST);
        }
        //逻辑删除只改变用户表的is_delete的值
        userMapper.removeUser(userIds);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUser(UserUpdateDto dto) {
        //判断用户名是否重复
        User userDB =userMapper.selectByEmail(dto.getEmail());
        if(userDB != null){
            if(!Objects.equals(userDB.getId(), dto.getId())){
                throw new BaseException(BasicEnum.DATA_EXIST);
            }
        }
        User user = BeanUtil.copyProperties(dto, User.class);
        //用户名为邮箱
        user.setUsername(dto.getEmail());
        //更新
        userMapper.updateUser(user);
        //先删除用户的角色
        userRoleMapper.deleteUserRoleByUserId(dto.getId());
        //再新增进去
        insertUserRole(dto.getId(),dto.getRoleVoIds());
    }

    @Override
    public String getUserIdByUsername(String username) {
        return userMapper.getUserIdByUsername(username);
    }

    //抽取出向关联表中添加数据的方法
    private void insertUserRole(Long userId , List<String> roleVoIds) {
        if(!CollectionUtils.isEmpty(roleVoIds)){
            //组装
            List<UserRole> collect = roleVoIds.stream().map(s -> {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Long.valueOf(s));
                userRole.setDataState(SuperConstant.DATA_STATE_0);
                return userRole;
            }).collect(Collectors.toList());
            //添加进角色用户关联表
            userRoleMapper.batchInsert(collect);
        }
    }
}
